# -*- coding: utf-8 -*-

from sanic import Sanic
from sanic.request import Request

from contextvars import ContextVar
from app.database import Session
from app.utils import regex_match

_base_model_session_ctx = ContextVar("session")


def denied_middleware_append(request: Request):
    return bool(regex_match(request.path, request.app.config.get("MIDDLEWARE_REGEX_WHITE_LIST", [])))


async def create_db_session_middleware(request: Request) -> None:
    print("request_middleware create_db_session")
    # 创建一个Session对象
    if denied_middleware_append(request=request):
        return
    request.ctx.session = Session()
    request.ctx.session_ctx_token = _base_model_session_ctx.set(request.ctx.session)


async def remove_db_session_middleware(request: Request, response) -> None:
    print("response_middleware remove_db_session")
    # 移除一个Session对象
    if hasattr(request.ctx, "session_ctx_token"):
        _base_model_session_ctx.reset(request.ctx.session_ctx_token)
        await request.ctx.session.close()


def install(app: Sanic) -> None:
    app.request_middleware.append(create_db_session_middleware)
    app.response_middleware.append(remove_db_session_middleware)
